package cn.b.sky.admin.utils;

import cn.b.sky.admin.model.SaUser;
import cn.b.sky.admin.security.ManagementAuthentication;
import cn.b.sky.admin.security.ManagementContextHolder;
import cn.b.sky.admin.security.context.ManagementContext;

import javax.servlet.http.HttpSession;

public class ManagementSecurity {
  /**
   * 取得当前用户的登录名,就是用户code， 如果当前用户未登录则返回空字符串.
   */
  public static String getCurrentUserCode() {
    ManagementAuthentication user = getAuthentication(null);
    return user == null ? "" : user.getUserCode();
  }

  /**
   * 取得当前用户的登录名,用户描述 如果当前用户未登录则返回空字符串.
   */
  public static String getCurrentUserText() {
    SaUser user = getCurrentUser();
    return user == null ? "" : user.getUserText();
  }

  /**
   * 取得当前用户, 返回值为User类
   */
  public static SaUser getCurrentUser() {
    
    ManagementAuthentication authentication = getAuthentication(null);

    if (authentication == null) {
      return null;
    }

    Object principal = authentication.getPrincipal();
    if (!(principal instanceof SaUser)) {
      return null;
    }
    return (SaUser) principal;

  }
  
  public static SaUser getCurrentUser(HttpSession session) {
    
    ManagementAuthentication authentication = getAuthentication(session);

    if (authentication == null) {

      return null;
    }

    Object principal = authentication.getPrincipal();
    if (!(principal instanceof SaUser)) {
      return null;
    }
    return (SaUser) principal;

  }
  /**
   * 取得Authentication, 如当前ManagementContext为空时返回null.
   */
  public static ManagementAuthentication getAuthentication(HttpSession session) {
    
    ManagementContext context = null;
    //从session获取
    if (session != null) {
      context = (ManagementContext) session.getAttribute(ManagementContextHolder.MANAGEMENT_SECURITY_CONTEXT);
    } else {
      context = ManagementContextHolder.getContext();
    }
    if (context == null) {
      return null;
    }

    return context.getAuthentication();
  }

  public static void clearContext() {
    ManagementContextHolder.clearContext();
  }
}
